/*
   Copyright 2010 Johan Hilding

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 */


package org.johanhil.flygtider.provider.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.johanhil.flygtider.R;
import org.johanhil.flygtider.provider.AirportDataProvider;

import android.content.Context;
import android.content.res.Resources;
import android.util.Log;

/*
 * Right now we split the resource on |, but there has to be a better way.
 */
public class StaticAirportDataProvider implements AirportDataProvider {
	private Context c;
	private static final String TAG = "Flygtider";
	private Map<String, String> airports = null;
	private List<String> airportNames = null; // we need this to keep them sorted.
	
	public StaticAirportDataProvider(Context c)
	{
		this.c = c;
		this.airports = new HashMap<String, String>(); 
		this.airportNames = new ArrayList<String>();
		populate();
	}
	
	/**
	 * Populates the internal data structures. This does all the work by fetching 
	 * the |-delimited strings from airports.xml, separating the fields and 
	 * putting them in the map.
	 */
	private void populate()
	{
		Resources res = c.getResources();
		if (res == null)
		{
			Log.e(TAG, "resources == null, cannot proceed w/ getting airports");
			return;
		}
		
		CharSequence[] airports = res.getTextArray(R.array.airports);
		
		// TODO perhaps this could be optimized, a lot of objects are created.
		for (CharSequence charSequence : airports)
		{
			String line = charSequence.toString();
			int delimiterPosition = line.indexOf('|');
			String name = line.substring(0, delimiterPosition);
			String url = line.substring(delimiterPosition+1);
			this.airports.put(name, url);
			this.airportNames.add(name);
		}
	}
	
	public List<String> getNames()
	{
		return airportNames;
	}
	
	public String getBaseUrl(String airportName)
	{
		return airports.get(airportName);
	}
}
